package com.vehiclesecure.service;

import com.vehiclesecure.model.User;
import com.vehiclesecure.repository.UserRepository;
import com.vehiclesecure.security.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserService implements UserDetailsService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final JwtService jwtService;

    @Autowired
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder,
            @Lazy AuthenticationManager authenticationManager, JwtService jwtService) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.authenticationManager = authenticationManager;
        this.jwtService = jwtService;
    }

    /**
     * 用户认证
     * 
     * @param email    用户邮箱
     * @param password 用户密码
     * @return JWT令牌
     */
    public String authenticate(String email, String password) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(email, password));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        User user = findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

        return jwtService.generateToken(user);
    }

    /**
     * 用户注册
     * 
     * @param user 用户对象
     * @return 注册成功的用户
     */
    public User registerUser(User user) {
        // 检查用户是否已存在
        if (userRepository.existsByEmail(user.getEmail())) {
            throw new RuntimeException("用户邮箱已被注册");
        }

        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 默认角色为USER
        if (user.getRole() == null) {
            user.setRole(User.Role.USER);
        }

        return userRepository.save(user);
    }

    /**
     * 根据邮箱查找用户
     * 
     * @param email 用户邮箱
     * @return 用户对象
     */
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    /**
     * 根据ID查找用户
     * 
     * @param id 用户ID
     * @return 用户对象
     */
    public Optional<User> getUserById(String id) {
        return userRepository.findById(id);
    }

    /**
     * 获取所有用户（管理员功能）
     * 
     * @return 用户列表
     */
    // public List<User> getAllUsers() {
    // return userRepository.findAll();
    // }
    public List<User> getAllUsers() {
        System.out.println("开始查询所有用户");
        List<User> users = userRepository.findAll();
        System.out.println("查询到用户数量: " + users.size());
        return users;
    }

    /**
     * 删除用户（管理员功能）
     * 
     * @param id 用户ID
     */
    public void deleteUser(String id) {
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在: " + id);
        }
        userRepository.deleteById(id);
    }

    /**
     * 检查用户是否绑定车辆
     * 
     * @param userId 用户ID
     * @return 是否绑定
     */
    public boolean hasVehicleBound(String userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return user.getVehicleIds() != null && !user.getVehicleIds().isEmpty();
    }

    /**
     * 获取用户绑定的车辆ID
     * 
     * @param userId 用户ID
     * @return 车辆ID列表
     */
    public List<String> getUserVehicleIds(String userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return user.getVehicleIds() != null ? user.getVehicleIds() : List.of();
    }

    /**
     * 根据邮箱加载用户详情
     * 
     * @param email 用户邮箱
     * @return 用户详情
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + email));
    }

    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    public User updateUserRole(String userId, String newRole) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        user.setRole(User.Role.valueOf(newRole));
        return userRepository.save(user);
    }

    /**
     * 更新用户信息
     * 
     * @param user 用户对象
     * @return 更新后的用户
     */
    public User updateUser(User user) {
        User existingUser = userRepository.findById(user.getId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 更新可修改的字段
        existingUser.setFirstName(user.getFirstName());
        existingUser.setLastName(user.getLastName());
        existingUser.setEmail(user.getEmail());
        existingUser.setVehicleIds(user.getVehicleIds());
        existingUser.setAllowedVendors(user.getAllowedVendors());

        // 如果提供了新密码，则更新密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        return userRepository.save(existingUser);
    }

    /**
     * 绑定车辆到用户（基于用户ID）
     * 
     * @param userId    用户ID
     * @param vehicleId 车辆ID
     * @return 更新后的用户
     */
    public User bindVehicleToUser(String userId, String vehicleId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 如果用户还没有车辆ID列表，则创建一个新列表
        if (user.getVehicleIds() == null) {
            user.setVehicleIds(new ArrayList<>());
        }
        
        // 如果车辆ID还不在用户的车辆列表中，则添加
        if (!user.getVehicleIds().contains(vehicleId)) {
            user.getVehicleIds().add(vehicleId);
        }

        return userRepository.save(user);
    }

    /**
     * 解除车辆绑定（基于用户ID）
     * 
     * @param userId 用户ID
     * @return 更新后的用户
     */
    public User unbindVehicleFromUser(String userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 解除绑定
        user.setVehicleIds(null);

        return userRepository.save(user);
    }

    /**
     * 绑定车辆到用户（基于邮箱）
     * 
     * @param email     用户邮箱
     * @param vehicleId 车辆ID
     * @return 更新后的用户
     */
    public User bindVehicleToUserByEmail(String email, String vehicleId) {
        User user = findByEmail(email)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (user.getVehicleIds() != null && !user.getVehicleIds().isEmpty()) {
            throw new RuntimeException("每个用户只能绑定一辆车");
        }

        List<String> vehicleIds = new ArrayList<>();
        vehicleIds.add(vehicleId);
        user.setVehicleIds(vehicleIds);

        return userRepository.save(user);
    }

    /**
     * 解除车辆绑定（基于邮箱）
     * 
     * @param email 用户邮箱
     * @return 更新后的用户
     */
    public User unbindVehicleFromUserByEmail(String email) {
        User user = findByEmail(email)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        user.setVehicleIds(new ArrayList<>());
        return userRepository.save(user);
    }
}